<?php
declare (strict_types=1);

namespace app\logic;

use app\model\Admin;
use app\service\PasswordService;
use app\service\TokenService;

class OauthLogic
{
    private function lockFile()
    {
        return root_path() . "/" . 'lock';
    }

    public function getLock()
    {
        return is_file($this->lockFile());
    }

    public function createLock()
    {
        return fopen($this->lockFile(), 'w');
    }

    /**
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function register()
    {
        $salt = rand(1000, 9999);
        $origin_password = (string)rand(100000, 999999);
        $password = PasswordService::getPassWord($origin_password, $salt);

        $admin = Admin::where('username', 'admin')->find();

        if ($admin) {
            $admin->password = $password;
            $admin->salt = $salt;
            $admin->token=null;
            $return = $admin->save();
        } else {
            $return = Admin::insert(['username' => 'admin',
                'password' => $password,
                'salt' => $salt]);
        }

        if (!$return) {
            throw new \Exception("初始化admin失败", 1002);
        }

        return $origin_password;
    }

    public function changePassword($params = [])
    {
        $Admin = new Admin();
        $admin = $Admin->getByUserName($params['username']);

        if (!$admin) throw new \Exception("管理员username找不到", 1000);

        $old_password = PasswordService::getPassWord($params['old_password'], $admin['salt']);

        if ($admin['password'] != $old_password) {
            throw new \Exception("密码错误", 1001);
        }

        $new_salt = rand(1000, 9999);
        $new_password = PasswordService::getPassWord($params['new_password'], $new_salt);

        $admin->salt = $new_salt;
        $admin->password = $new_password;
        $admin->token = null;
        return $admin->save();
    }

    public function login($params = [])
    {
        $Admin = new Admin();
        $admin = $Admin->getByUserName($params['username']);

        if (!$admin) throw new \Exception("管理员username找不到", 1000);

        $salt = $admin['salt'];
        $db_password = $admin['password'];

        unset($admin['salt'], $admin['password']);
        $password_result = PasswordService::getPassWord($params['password'], $salt);

        if ($db_password === $password_result) {
            $TokenService = new TokenService();
            $token = $TokenService->updateToken($admin['id']);
            return $token;
        }

        return false;
    }

    /**
     * @param $token
     * @return bool
     * @throws \Exception
     */
    public function logout($token)
    {
        $TokenService = new TokenService();
        return $TokenService->delToken($token);
    }
}